//
//  HJCancellationController.m
//  KaiChat
//
//  Created by lx on 2023/10/19.
//

#import "HJCancellationController.h"
#import "HJMinePresent.h"
#import "HJUIAlertController.h"
#import "HJAlertController.h"
#import "HJCancellationCell.h"
#import "YYText.h"
#import "HJWebViewController.h"
#import "QMUIButton.h"
#import "HJCancellationKaiPayErrorController.h"

@interface HJCancellationController ()

@property (nonatomic, strong) UIScrollView *mainView;
@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, assign) BOOL isAgreement;
@property (nonatomic, weak) HJStyle1Button *cancellationButton;

@end

@implementation HJCancellationController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationBar.title = @"Delete account";
    
    UIView *bottomView = [[UIView alloc] init].addTo(self.view);
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
        make.height.offset(102 + TabbarSafeBottomMargin);
        make.left.right.offset(0);
    }];
    
    HJStyle1Button *cancellationButton = [HJStyle1Button buttonWithSuperView:bottomView font:UIFontMediumMake(14) color:nil title:@"Cancellation！"];
    [cancellationButton addTarget:self action:@selector(didClickCancellationButton) forControlEvents:UIControlEventTouchUpInside];
    cancellationButton.enabled = NO;
    [cancellationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.height.offset(buttonHeight);
        make.bottom.inset(10 + TabbarSafeBottomMargin);
    }];
    
    QMUIButton *agreeButton = [QMUIButton addToView:bottomView];
    [agreeButton addTarget:self action:@selector(didClickAgreeButton:) forControlEvents:UIControlEventTouchUpInside];
    [agreeButton setImage:[UIImage imageNamed:@"box_icon"] forState:UIControlStateNormal];
    [agreeButton setImage:[UIImage imageNamed:@"box_select_icon"] forState:UIControlStateSelected];
    [agreeButton setImagePosition:QMUIButtonImagePositionLeft];
    agreeButton.spacingBetweenImageAndTitle = 4;
    [agreeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(leftRightMargin);
        make.height.offset(16);
        make.width.offset(16);
        make.top.offset(15);
    }];
    
    YYLabel *textLabel = [[YYLabel alloc] initWithFrame:CGRectMake(10, KNavBarHight + 40, 200, 100)];
    textLabel.numberOfLines = 0;
    textLabel.font = UIFontMake(12);
    textLabel.textColor = UIColor.tj_868391Color;
    textLabel.backgroundColor = UIColor.clearColor;
    textLabel.preferredMaxLayoutWidth = KScreenWidth - 26 - leftRightMargin * 2;//最大宽度
    [bottomView addSubview:textLabel];
    [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(agreeButton.mas_right).offset(5);
        make.top.equalTo(agreeButton);
        make.right.inset(leftRightMargin);
    }];
    
    NSString *contentString = @"I have read and agreed《Deletion Agreement》";
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:contentString attributes:@{
        NSFontAttributeName: UIFontMake(12),
        NSForegroundColorAttributeName: UIColor.tj_868391Color
    }];
    
    TJWeakify(self)
    [attributedString yy_setTextHighlightRange:[contentString rangeOfString:@"I have read and agreed"] color:UIColor.tj_868391Color backgroundColor:UIColor.clearColor  tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakself didClickAgreeButton:agreeButton];
    }];
    
    [attributedString yy_setTextHighlightRange:[contentString rangeOfString:@"《Deletion Agreement》"] color:UIColor.tj_333333Color backgroundColor:UIColor.clearColor  tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        
        HJWebViewController *webViewController = [[HJWebViewController alloc] init];
        webViewController.url = @"https://kaichat.io/account";
        webViewController.title = @"Deletion Agreement";
        [weakself.navigationController pushViewController:webViewController];
        
    }];

    textLabel.attributedText = attributedString;
    

    UIView *headerView = [[UIView alloc] init];

    UILabel *titleLabel = [UILabel lableWithSuperView:headerView font:UIFontMediumMake(20) color:UIColor.tj_333333Color title:@"User Delete Reminder" textAlignment:NSTextAlignmentLeft];
    titleLabel.frame = CGRectMake(0, 0, KScreenWidth - leftRightMargin * 2, 10);
    [titleLabel sizeToFit];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(leftRightMargin);
        make.top.offset(10);
    }];
    
    UILabel *bodyLabel = [UILabel lableWithSuperView:headerView font:UIFontMake(14) color:UIColor.tj_333333Color title:@"Before proceeding with the deletion, KAI will verify your account to ensure the security of your account and assets:" textAlignment:NSTextAlignmentLeft];
    bodyLabel.numberOfLines = 0;
    bodyLabel.frame = CGRectMake(0, 0, KScreenWidth - leftRightMargin * 2, 10);
    [bodyLabel sizeToFit];
    [bodyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel);
        make.top.equalTo(titleLabel.mas_bottom).offset(6);
        make.right.inset(leftRightMargin);
    }];
        
    headerView.frame = CGRectMake(0, 0, KScreenWidth, 10 + titleLabel.tj_height + bodyLabel.tj_height + 6 + 20);
    self.tableView.tableHeaderView = headerView;

    [self.tableView registerClass:HJCancellationCell.class forCellReuseIdentifier:@"HJCancellationCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = cellHeight;
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(KNavBarHight);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    
    _cancellationButton = cancellationButton;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJCancellationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJCancellationCell" forIndexPath:indexPath];
    cell.model = self.datas[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJCellModel *model = self.datas[indexPath.row];
    return model.height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HJCellModel *model = self.datas[indexPath.row];
    HJCancellationCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    void (^selectCell)(BOOL value) = ^(BOOL value) {
        model.isSelect = value;
        cell.model = model;
        [self updateCancellationButtonState];
    };

    if ([model.identifier isEqualToString:@"Kaiearn"]) {
        if (model.isSelect) {
            selectCell(NO);
        } else {
            [HJHUD showGraceTimeLoadingInView:self.view];
            [HJMinePresent kaiearmIsComplete:^(BOOL res, NSError * _Nullable error) {
                if (error) {
                    [HJHUD showErrorMessage:error.localizedFailureReason];
                    return;
                };
                if (res) {
                    selectCell(res);
                } else {
                    [HJAlertController alertInController:getMainController() title:@"Important-Note" message:@"Please settle your Kaiearn order before proceeding with the deletion." left:^(HJAlertAction * _Nonnull action) {
                        action.title = @"Cancel";
                        action.titleColor = UIColor.tj_868391Color;
                    } right:^(HJAlertAction * _Nonnull action) {
                        action.title = @"Take action";
                        action.titleColor = UIColor.tj_mainColor;
                        [action setHandler:^{
                            [self.navigationController popToRootViewControllerAnimated:NO];
                            [getMainController() tj_setSelectedIndex:1];
                        }];
                    }];
                }
            }];
        }
        return;
    }
    
    if ([model.identifier isEqualToString:@"KaiPay"]) {
        if (model.isSelect) {
            selectCell(NO);
        } else {
//            [HJHUD showGraceTimeLoadingInView:self.view];
//            [HJMinePresent getKaiPayBalanceComplete:^(NSString * _Nullable balance, NSError * _Nullable error) {
//                if (error) {
//                    [HJHUD showErrorMessage:error.localizedFailureReason];
//                    return;
//                };
//                if (balance.floatValue == 0) {
//                    selectCell(YES);
//                } else {
//                    HJCancellationKaiPayErrorController *cancellationKaiPayErrorController = [[HJCancellationKaiPayErrorController alloc] init];
//                    [cancellationKaiPayErrorController showInController:self];
//                    [cancellationKaiPayErrorController setSelectComplete:^(BOOL isAbandon) {
//                        if (isAbandon) {
//                            selectCell(YES);
//                        } else {
//                            [self.navigationController popToRootViewControllerAnimated:NO];
//                            [getMainController() tj_setSelectedIndex:1];
//                        }
//                    }];
//                }
//            }];
            selectCell(YES);
        }
        return;
    }
    
    if ([model.identifier isEqualToString:@"MPC"]) {
        if (model.isSelect) {
            selectCell(NO);
        } else {
//            [HJHUD showGraceTimeLoadingInView:self.view];
//            [HJMinePresent MPCIsAbleDestroyedComplete:^(BOOL res, NSError * _Nullable error) {
//                if (error) {
//                    [HJHUD showErrorMessage:error.localizedFailureReason];
//                    return;
//                };
//                
//                if (res) {
//                    selectCell(res);
//                } else {
//                    [HJAlertController alertInController:getMainController() title:@"Important-Note" message:@"Please destroy your MPC wallet before proceeding with the deletion." left:^(HJAlertAction * _Nonnull action) {
//                        action.title = @"Cancel";
//                        action.titleColor = UIColor.tj_868391Color;
//                    } right:^(HJAlertAction * _Nonnull action) {
//                        action.title = @"Take action";
//                        action.titleColor = UIColor.tj_mainColor;
//                        [action setHandler:^{
//                            [self.navigationController popToRootViewControllerAnimated:NO];
//                            [getMainController() tj_setSelectedIndex:2];
//                        }];
//                    }];
//                }
//            }];
            selectCell(YES);
        }
        return;
    }
    
    model.isSelect = !model.isSelect;
    selectCell(model.isSelect);
}


- (void)didClickAgreeButton:(UIButton *)button {
    button.selected = !button.selected;
    _isAgreement = button.selected;
    
    [self updateCancellationButtonState];
}

- (void)updateCancellationButtonState {
    BOOL isAllSelect = YES;
    for (HJCellModel *model in self.datas) {
        if (!model.isSelect) {
            isAllSelect = NO;
            break;
        }
    }
    _cancellationButton.enabled = isAllSelect && _isAgreement;
}


- (void)didClickCancellationButton {
    [HJAlertController alertInController:getMainController() title:@"Confirm Deletion" message:@"After confirming the deletion, the account will be immediately and permanently deleted, and cannot be used again." left:^(HJAlertAction * _Nonnull action) {
        action.title = @"Cancel";
        action.titleColor = UIColor.tj_868391Color;
    } right:^(HJAlertAction * _Nonnull action) {
        action.title = @"Confirm";
        action.titleColor = UIColor.tj_mainColor;
        [action setHandler:^{
            [HJMinePresent revokedComplete:^(NSError * _Nullable error, NSString *message) {
                if (!error) {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(300 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
                        [HJHUD showSucceedMessage:@"Deletion successful"];
                    });
                }
            }];
   
        }];
    }];
}

- (NSArray *)datas {
    if (!_datas) {
        _datas = @[
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.identifier = @"accountState";
                model.text = @"I confirm account security";
                model.subText = @"The current account has no risk issues, and after deletion, the login and transaction functionalities of the account will no longer be provided.";
                CGSize subTextSize = [model.subText getStringSizeWithWidth:KScreenWidth - 66 font:UIFontMake(12)];
                model.height = 24 + subTextSize.height + 15;
            }],
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.identifier = @"terminate";
                model.text = @"I confirm the termination of my affiliation";
                model.subText = @"All account information will be anonymized and deleted, including personal data, message records, historical data, and administrative identity. It will not be possible to retrieve them.";
                CGSize subTextSize = [model.subText getStringSizeWithWidth:KScreenWidth - 66 font:UIFontMake(12)];
                model.height = 24 + subTextSize.height + 15;
            }],
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.identifier = @"Kaiearn";
                model.text = @"Kaiearn Order Settled";
                model.subText = @"The Kaiearn account's order status has been fully settled, with no pending items.";
                CGSize subTextSize = [model.subText getStringSizeWithWidth:KScreenWidth - 66 font:UIFontMake(12)];
                model.height = 24 + subTextSize.height + 15;
            }],
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.identifier = @"KaiPay";
                model.text = @"KaiPay Issue Resolved";
                model.subText = @"You have either processed the KaiPay assets or relinquished the remaining assets (or have not activated them), and the assets will be automatically cleared upon verification.";
                CGSize subTextSize = [model.subText getStringSizeWithWidth:KScreenWidth - 66 font:UIFontMake(12)];
                model.height = 24 + subTextSize.height + 15;
            }],
            [HJCellModel modelWithBlock:^(HJCellModel * _Nonnull model) {
                model.identifier = @"MPC";
                model.text = @"MPC Wallet Destroyed";
                model.subText = @"You have either destroyed the MPC wallet (or it was not activated), and there are no pending assets in KAI.";
                CGSize subTextSize = [model.subText getStringSizeWithWidth:KScreenWidth - 66 font:UIFontMake(12)];
                model.height = 24 + subTextSize.height + 15;
            }],
        ];
    }
    return _datas;
}


@end
